package com.sumec.controller;

import com.sumec.util.CommonResult;
import com.sumec.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * web层通用数据处理
 *
 * @author huyucai
 */
public class BaseController {
    private final static Logger log = LoggerFactory.getLogger(BaseController.class);

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 返回成功
     */
    public CommonResult success() {
        return CommonResult.success();
    }

    /**
     * 返回成功消息
     */
    public CommonResult success(String message) {
        return CommonResult.success(message);
    }

    /**
     * 返回成功数据
     */
    public CommonResult success(Object data) {
        return CommonResult.success(data);
    }

    /**
     * 返回成功消息和数据
     */
    public CommonResult success(String message, Object data) {
        return CommonResult.success(message, data);
    }

    /**
     * 返回失败消息
     */
    public CommonResult error() {
        return CommonResult.error();
    }

    /**
     * 返回失败消息
     */
    public CommonResult error(String message) {
        return CommonResult.error(message);
    }

    /**
     * 返回失败码消息
     */
    public CommonResult error(CommonResult.RespCodeEnum type, String message) {
        return new CommonResult(type, message);
    }
}
